var Api = require('utils/api.js');
App({
  globalData: {
	
  },

  onLaunch: function () {
    var that = this
    var user = wx.getStorageSync('user') || {};
    var userInfo = wx.getStorageSync('userInfo') || {};
    if (!user.openid || Date.parse(new Date()) / 1000 > (user.expires_in - 600)) {
      wx.login({
        success: function (res) {
          if (res.code) {
            var url = Api.HOST + 'wechat.php?s=Applet/getopenid';
            var data = {};
            data.code = res.code;
            Api.fetchPost(url, data, (err, res) => {
              var obj = {};
              obj.openid = res.openid;
              obj.expires_in = Date.parse(new Date()) / 1000 + res.expires_in;
              wx.setStorageSync('user', obj);//存储openid
            });
          } else {
            console.log('获取用户登录态失败！' + res.errMsg)
          }       
        }
      });
    }
  },
  
  getUserInfo: function (cb) {
    var that = this;
    if (this.globalData.userInfo) {
      typeof cb == "function" && cb(this.globalData.userInfo)
    } else {
      //调用登录接口
      wx.login({
        success: function () {
          wx.getUserInfo({
            success: function (res) {
              that.globalData.userInfo = res.userInfo
              typeof cb == "function" && cb(that.globalData.userInfo)
              wx.setStorageSync('userInfo', res.userInfo);
            }
          })
        }
      })
    }
  },
  
})